package com.ruoyi.lm.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.lm.domain.*;
import com.ruoyi.lm.service.*;
import com.ruoyi.lm.service.impl.WxTemplateMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.ruoyi.common.utils.Sha1Util.getNonceStr;


/**
 * 用户Controller
 * 
 * @author ruoyi
 * @date 2020-09-02
 */
@Controller
@RequestMapping(value = "/phone/lm/wxPay")
public class WxPayController extends BaseController {

    @Autowired
    private ILmActivityService lmActivityService;

    @Autowired
    private ILmUsersignService lmUsersignService;

    @Autowired
    private ILmLevelpackageService lmLevelpackageService;

    @Autowired
    private ILmUserService lmUserService;

    @Autowired
    private ILmUserlevelpackageService lmUserlevelpackageService;

    @Autowired
    private ILmConfService lmConfService;

    @Autowired
    private ILmUserwithdrawService lmUserwithdrawService;

    @Autowired
    private ILmWithdrawrecordService lmWithdrawrecordService;




    //微信支付商户开通后 微信会提供appid和appsecret和商户号partner
    @Value("${wxConfig.appId}")
    private String appId;

    @Value("${wxConfig.appSecret}")
    private String appSecret;

    @Value("${wxConfig.partner}")
    private String partner;

    @Value("${wxConfig.partnerKey}")
    private String partnerKey;

    @Value("${wxConfig.notifyUrl}")
    private String notifyUrl;



//    private static final String appid = "wx72f8c2bab90e6c90";
//    private static final String appsecret = "55f6ba245e76fc94b97e335bb439438e";
//    private static final String partner = "1528613081";
//    private static final String partnerkey = "dfte9809FWEJL239E4830FWKFCD3DE89";

    //微信支付成功后通知地址 必须要求80端口并且地址不能带参数
//    private static final String notifyurl = "/phone/lm/wxPay/notify";


    /**
     * 微信支付
     * @param openid
     * @param attach  levelpackage:套餐包  activity:活动报名
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/wxPay")
    public List<Map<String, Object>> wxPay(String openid, String attach, String id, String userId, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        List<Map<String, Object>> commlist = new ArrayList<Map<String, Object>>();
//        String callback = request.getParameter("callback");
//        System.out.println("callback"+callback+"********************");
        Map<String, Object> resultmap = new HashMap<String, Object>();
        //微信支付jsApi
        System.out.println(openid);
        String orderId = IdWorker.getId();
        WxPayDto tpWxPay = new WxPayDto();
        tpWxPay.setOpenId(openid);
        String totalfee = "";
        if ("levelpackage".equals(attach)) {
            tpWxPay.setBody("购买套餐包");

            //获取套餐包价格
            LmLevelpackage lmLevelpackage = lmLevelpackageService.selectLmLevelpackageById(id);
            totalfee = String.valueOf(lmLevelpackage.getPackagePrice());
        } else if ("activity".equals(attach)) {
            tpWxPay.setBody("活动报名");

            //获取报名费用
            LmActivity activity = lmActivityService.selectLmActivityById(id);
            totalfee = activity.getActivityPrice().toString();
        }
//        totalfee = "0.01";
        attach = attach + "_" + id + "_" + userId;
        tpWxPay.setOrderId(orderId);
        tpWxPay.setSpbillCreateIp("127.0.0.1");
        tpWxPay.setTotalFee(totalfee);
        tpWxPay.setAttach(attach);

        String returnresult = getPackage(tpWxPay);
        System.out.println(returnresult + "-----------------------------------returnresult");
        String[] resultarray = returnresult.split(",");
        for (String item : resultarray) {
            String[] temp = item.split(":");
            System.out.println("item" + item);
            System.out.println("temp[0]" + temp[0] + "temp[1]" + temp[1]);
            temp[0] = temp[0].replaceAll("\"", "");
            temp[1] = temp[1].replaceAll("\"", "");
            resultmap.put(temp[0], temp[1]);
        }
        commlist.add(resultmap);

        System.out.println("json**********" + commlist + "***************");
        return commlist;
    }



    /**
     * 获取请求预支付id报文
     *
     * @return
     */
    public String getPackage(WxPayDto tpWxPayDto) {

        String openId = tpWxPayDto.getOpenId();
        // 1 参数
        // 订单号
        String orderId = tpWxPayDto.getOrderId();
        // 附加数据 原样返回
        String attach = tpWxPayDto.getAttach();
        // 总金额以分为单位，不带小数点
        String totalFee = getMoney(tpWxPayDto.getTotalFee());

        // 订单生成的机器 IP
        String spbill_create_ip = tpWxPayDto.getSpbillCreateIp();
//        String notify_url = "https://www.zzzsyh.com/cs_pay/wxpay/notify";
        String trade_type = "JSAPI";

        // ---必须参数
        // 商户号
        String mch_id = partner;
        // 随机字符串
        String nonce_str = IdWorker.getId();

        // 商品描述根据情况修改
        String body = tpWxPayDto.getBody();

        // 商户订单号
        String out_trade_no = orderId;

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", appId);
        packageParams.put("attach", attach);
        packageParams.put("body", body);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);
//        packageParams.put("notify_url", "http://n239v16088.qicp.vip/cs_pay/wxpay/notify");
        packageParams.put("notify_url", notifyUrl);
        packageParams.put("openid", openId);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("total_fee", totalFee);
        packageParams.put("trade_type", trade_type);


        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(appId, appSecret, partnerKey);

        String sign = reqHandler.createSign(packageParams);
        System.out.println("第一次签名------------------------------" + sign);
        String xml = "<xml>" + "<appid>" + appId + "</appid>" + "<mch_id>"
                + mch_id + "</mch_id>" + "<nonce_str>" + nonce_str
                + "</nonce_str>" + "<sign>" + sign + "</sign>"
                + "<body><![CDATA[" + body + "]]></body>"
                + "<out_trade_no>" + out_trade_no
                + "</out_trade_no>" + "<attach>" + attach + "</attach>"
                + "<total_fee>" + totalFee + "</total_fee>"
                + "<spbill_create_ip>" + spbill_create_ip
                + "</spbill_create_ip>" + "<notify_url>" + notifyUrl
                + "</notify_url>" + "<trade_type>" + trade_type
                + "</trade_type>" + "<openid>" + openId + "</openid>"
                + "</xml>";
        String prepay_id = "";
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";


        prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);

        System.out.println("获取到的预支付ID：" + prepay_id);


        //获取prepay_id后，拼接最后请求支付所需要的package

        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        String packages = "prepay_id=" + prepay_id;
        finalpackage.put("appId", appId);
        finalpackage.put("timeStamp", timestamp);
        finalpackage.put("nonceStr", nonce_str);
        finalpackage.put("package", packages);
        finalpackage.put("signType", "MD5");
        //要签名
        String finalsign = reqHandler.createSign(finalpackage);
        System.out.println("第二次签名------------------------------" + finalsign);
        String finaPackage = "\"appId\":\"" + appId + "\",\"timeStamp\":\"" + timestamp
                + "\",\"nonceStr\":\"" + nonce_str + "\",\"package\":\""
                + packages + "\",\"signType\" : \"MD5" + "\",\"paySign\":\""
                + finalsign + "\"";

        System.out.println("V3 jsApi package:" + finaPackage);
        return finaPackage;
    }

    /**
     * 微信公众号 提现转账
     * @param m
     * @return
     * @throws Exception
     */
    public Map<String, Object> sendPayWithdraw(Map<String, String> m)throws Exception {

        String openId = m.get("openid");
        // 1 参数
        // 订单号
        String orderId = m.get("orderId");
        // 总金额以分为单位，不带小数点
        String totalFee = getMoney(m.get("money"));

        // 订单生成的机器 IP
        String spbill_create_ip = m.get("spbillCreateIp");

        // ---必须参数
        // 商户号
        String mch_id = partner;
        // 随机字符串
        String nonce_str = getNonceStr();

        String desc = "提现转账";

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("mch_appid", appId);
        packageParams.put("mchid", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("desc", desc);
        packageParams.put("partner_trade_no", orderId);
        // 这里写的金额为1 分到时修改
        packageParams.put("amount", totalFee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("check_name", "NO_CHECK");
        packageParams.put("openid", openId);

        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(appId, appSecret, partnerKey);

        String sign = reqHandler.createSign(packageParams);
        logger.info("第一次签名------------------------------" + sign);
        System.out.println("第一次签名------------------------------" + sign);
        String xml = "<xml>" + "<mch_appid>" + appId + "</mch_appid>" + "<mchid>"
                + mch_id + "</mchid>" + "<nonce_str>" + nonce_str
                + "</nonce_str>"
                + "<partner_trade_no>" + orderId + "</partner_trade_no>"
                + "<openid>" + openId + "</openid>"
                + "<check_name>NO_CHECK</check_name>"
                + "<amount>" + totalFee + "</amount>"
                + "<desc>"+ desc +"</desc>"
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                + "<sign>" + sign + "</sign>"
                + "</xml>";
        String createOrderURL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";


        Map<String, Object> map = new GetWxOrderno().sendPost(createOrderURL, xml);
        logger.info("info---------------------------------------------------------获取到的预支付ID：" + map);
        System.out.println("获取到的预支付ID：" + map);

        return map;
    }

    /**
     * 元转换成分
     *
     * @param amount
     * @return
     */
    public static String getMoney(String amount) {
        if (amount == null) {
            return "";
        }
        // 金额转化为分为单位
        String currency = amount.replaceAll("\\$|\\￥|\\,", "");  //处理包含, ￥ 或者$的金额
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0l;
        if (index == -1) {
            amLong = Long.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
        } else if (length - index == 2) {
            amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong.toString();
    }


    /**
     * 微信回调
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    @ResponseBody
    public String notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, String> result = new HashMap<String, String>();
        Map<String, String> params = null;
        String returnxml = "";
        InputStream inputStream;
        StringBuffer sb = new StringBuffer();
        //以字节流的形式读取request中的数据
        inputStream = request.getInputStream();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
        inputStream.close();
        params = WXPayUtil.xmlToMap(sb.toString());
        logger.info("1.notify-params>>>>>>>>>>>:" + params);

        String returnCode = params.get("return_code");
        logger.info("3.returnCode:" + returnCode);
        if (returnCode.equals("SUCCESS")) {
            //判断签名是否正确
            boolean flag = isResponseSignatureValid(params);
            logger.info("2.notify-flag:" + flag);
            if (flag) {
                //获取微信订单号
                String transactionId = params.get("transaction_id");
                //获取商户订单号
                String outTradeNo = params.get("out_trade_no");
                //附加信息原路返回   recharge:充值 order:订单
                String attach = params.get("attach");
                logger.info("aaa====================================" + transactionId);
                logger.info("bbb====================================" + outTradeNo);
                logger.info("ccc====================================" + attach);
                //TODO  业务逻辑
                String attachs[] = attach.split("_");
                String id = attachs[1];
                String userId = attachs[2];
                attach = attachs[0];//levelpackage 套餐包   activity活动报名


                if ("levelpackage".equals(attach)) {
                    //获取套餐包
                    LmLevelpackage lmLevelpackage = lmLevelpackageService.selectLmLevelpackageById(id);
                    LmUser user = lmUserService.selectLmUserById(userId);
                    user.setPackageTimes(user.getPackageTimes() + lmLevelpackage.getPackageTimes());
                    lmUserService.updateLmUser(user);

                    //保存用户购买套餐记录
                    LmUserlevelpackage userlevelpackage = new LmUserlevelpackage();
                    userlevelpackage.setId(IdWorker.getId());
                    userlevelpackage.setUserId(userId);
                    userlevelpackage.setPackageId(id);
                    userlevelpackage.setPackageTimes(lmLevelpackage.getPackageTimes());
                    userlevelpackage.setCreateTime(new Date());
                    userlevelpackage.setTranstionId(transactionId);
                    userlevelpackage.setPackagePrice(Float.valueOf(lmLevelpackage.getPackagePrice()));
                    lmUserlevelpackageService.insertLmUserlevelpackage(userlevelpackage);

                    String pId = user.getUserPId();
                    if(EmptyUtils.isNotEmpty(pId)){
                        LmUser userP = lmUserService.selectLmUserById(pId);
                        if(userP != null){
                            //获取提成比例
                            LmConf conf = lmConfService.selectLmConfList(new LmConf()).get(0);
                            float withdraw_rate = Float.valueOf(conf.getWithdrawRate())/100;

                            //保存提成记录
                            LmUserwithdraw userwithdraw = new LmUserwithdraw();
                            userwithdraw.setId(IdWorker.getId());
                            userwithdraw.setUserId(pId);
                            userwithdraw.setWithdrawUser(userId);
                            float withdraw_sum = 0;
                            withdraw_sum = BigDecimalUtil.OperationASMD(withdraw_rate,lmLevelpackage.getPackagePrice(), BigDecimalUtil.BigDecimalOprations.multiply,2, BigDecimal.ROUND_HALF_UP).floatValue();
                            userwithdraw.setCreateTime(new Date());
                            userwithdraw.setWithdrawSum(withdraw_sum);
                            lmUserwithdrawService.insertLmUserwithdraw(userwithdraw);

                            //保存邀请人用户余额
                            double userBalance = Double.valueOf(userP.getUserBalance());
                            userBalance += withdraw_sum;
                            userP.setUserBalance(String.valueOf(BigDecimalUtil.decimalTwo(userBalance)));
                            lmUserService.updateLmUser(userP);

                        }
                    }




                } else if ("activity".equals(attach)) {
                    LmUser user = lmUserService.selectLmUserById(userId);

                    //获取报名
                    LmActivity activity = lmActivityService.selectLmActivityById(id);
                    LmActivity activity1 = new LmActivity();
                    String enjoyNum = String.valueOf(activity.getEnjoyNum());
                    if(EmptyUtils.isNotEmpty(enjoyNum)){
                        activity1.setEnjoyNum(Integer.valueOf(enjoyNum) + 1);
                    }else{
                        activity1.setEnjoyNum(1);
                    }
                    activity1.setId(id);

                    lmActivityService.updateLmActivity(activity1);


                    //保存用户报名信息
                    LmUsersign usersign = new LmUsersign();
                    usersign.setId(IdWorker.getId());
                    usersign.setSignType("2");
                    usersign.setSignId(id);
                    usersign.setUserId(userId);
                    usersign.setActivityPrice(Long.valueOf(activity.getActivityPrice()));
                    usersign.setTranstionId(transactionId);
                    usersign.setCreateTime(new Date());
                    usersign.setSignStatus("0");
                    lmUsersignService.insertLmUsersign(usersign);

                    userId = activity.getUserId();
                    LmUser user1 = lmUserService.selectLmUserById(userId);
                    WxTemplateMsgService wxTemplateMsgService = new WxTemplateMsgService();
                    wxTemplateMsgService.send_template_message(user1.getOpenId(), appId, appSecret, "活动");
                }


                result.put("return_code", "SUCCESS");
                result.put("return_msg", "支付成功");
                logger.info("4.订单：" + outTradeNo + " 交易完成" + ">>>" + transactionId);
            } else {
                result.put("return_code", "FAIL");
                result.put("return_msg", "签名失败");
                logger.info("签名验证失败>>>>>>>>>>>>");
            }
        } else {
            result.put("return_code", "FAIL");
            result.put("return_msg", "支付失败");
            logger.info("");
        }
        returnxml = WXPayUtil.mapToXml(result);
        return returnxml;
    }


    public boolean isResponseSignatureValid(Map<String, String> param) throws Exception {
        return WXPayUtil.isSignatureValid(param, partnerKey, WXPayConstants.SignType.MD5);
    }


    /**
     * 用户转账申请
     * @param userId
     * @param money
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/userWithdraw")
    @ResponseBody
    @Transactional
    public AjaxResult userWithdraw(String userId, String money) throws Exception{
        LmUser user = lmUserService.selectLmUserById(userId);
        float balacne = Float.valueOf(user.getUserBalance());
        float _money = Float.valueOf(money);
        if(balacne >= _money){
            String openid = user.getOpenId();
            Map<String, String> m = new HashMap<>();
            m.put("openid",openid);
            m.put("orderId",IdWorker.getId());
            m.put("money",money);
            m.put("spbillCreateIp","123.149.42.90");

            //暂时屏蔽付款
            Map<String, Object> responseMap = null;
            String transactionId = "";
            responseMap = sendPayWithdraw(m);
            if(responseMap != null && responseMap.size() > 0){
                if("SUCCESS".equals(responseMap.get("result_code").toString())){
                    transactionId = responseMap.get("partner_trade_no").toString();
                    System.out.println("调用成功");
                    //TODO  操作数据库
                    balacne = BigDecimalUtil.OperationASMD(balacne,_money, BigDecimalUtil.BigDecimalOprations.subtract,2, BigDecimal.ROUND_HALF_UP).floatValue();
                    user.setUserBalance(String.valueOf(balacne));
                    lmUserService.updateLmUser(user);

                    LmWithdrawrecord withdrawrecord = new LmWithdrawrecord();
                    withdrawrecord.setId(IdWorker.getId());
                    withdrawrecord.setUserId(userId);
                    withdrawrecord.setTranctionsId(transactionId);
                    withdrawrecord.setCreateTime(new Date());
                    withdrawrecord.setWithdrawSum(_money);
                    lmWithdrawrecordService.insertLmWithdrawrecord(withdrawrecord);


                    return success();
                }else{
                    String err_code = responseMap.get("err_code").toString();
                    String msg = "操作失败";
                    switch (err_code){
                        case "AMOUNT_LIMIT":msg += ",金额超限!";break;
                        case "NOTENOUGH":msg += ",您的付款帐号余额不足或资金未到账!";break;
                        case "SYSTEMERROR":msg += ",系统繁忙，请稍后再试!";break;
                        case "V2_ACCOUNT_SIMPLE_BAN":msg += ",用户微信支付账户未知名，无法付款!";break;
                        case "SENDNUM_LIMIT":msg += ",该用户今日付款次数超过限制,如有需要请登录微信支付商户平台更改API安全配置!";break;
                        case "MONEY_LIMIT":msg += ",已经达到今日付款总额上限/已达到付款给此用户额度上限!";break;
                        case "FREQ_LIMIT":msg += ",超过频率限制，请稍后再试!";break;
                        default:break;
                    }
                    return error(msg);
                }
            }
        }else{
            return error("余额不足");
        }
        return error();
    }

    @RequestMapping("/getWxShare")
    public @ResponseBody Map<String, String> init(String url)throws Exception{
//        url = URLEncoder.encode(url, "utf-8");
        String jsapi_ticket = WeiXinUtil.getJsapiTicket(WeiXinUtil.getAccessToken(appId, appSecret).getAccessToken());



        Map<String, String> ret = sign(jsapi_ticket, url);

        System.out.println("currurl = "+ url);

        // 注意 URL 一定要动态获取，不能 hardcode
//		for (Map.Entry entry : ret.entrySet()) {
//			System.out.println(entry.getKey() + ", " + entry.getValue());
//		}
        System.out.println("signature =" + ret.get("signature"));
        return ret;
    }




    public Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        // 注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("appId",appId);
//        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


    /**
     * 转账
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/transfer")
    @ResponseBody
    @Transactional
    public AjaxResult transfer(String id) throws Exception{
        LmWithdrawrecord withdrawrecord = lmWithdrawrecordService.selectLmWithdrawrecordById(id);
        String userId = withdrawrecord.getUserId();
        LmUser user = lmUserService.selectLmUserById(userId);
        String openid = user.getOpenId();
        Map<String, String> m = new HashMap<>();
        m.put("openid",openid);
        m.put("orderId",IdWorker.getId());
        m.put("money",String.valueOf(withdrawrecord.getWithdrawSum()));
        m.put("spbillCreateIp","123.149.42.90");

        //暂时屏蔽付款
        Map<String, Object> responseMap = null;
        String transactionId = "";
        responseMap = sendPayWithdraw(m);
        if(responseMap != null && responseMap.size() > 0){
            if("SUCCESS".equals(responseMap.get("result_code").toString())){
                transactionId = responseMap.get("partner_trade_no").toString();
                System.out.println("调用成功");
                //TODO  操作数据库

                LmWithdrawrecord withdrawrecord1 = new LmWithdrawrecord();
                withdrawrecord.setId(withdrawrecord.getId());
                withdrawrecord.setUpdateTime(new Date());
                withdrawrecord.setWithdrawStatus("已提现");
                lmWithdrawrecordService.insertLmWithdrawrecord(withdrawrecord);


                return success();
            }else{
                String err_code = responseMap.get("err_code").toString();
                String msg = "操作失败";
                switch (err_code){
                    case "AMOUNT_LIMIT":msg += ",金额超限!";break;
                    case "NOTENOUGH":msg += ",您的付款帐号余额不足或资金未到账!";break;
                    case "SYSTEMERROR":msg += ",系统繁忙，请稍后再试!";break;
                    case "V2_ACCOUNT_SIMPLE_BAN":msg += ",用户微信支付账户未知名，无法付款!";break;
                    case "SENDNUM_LIMIT":msg += ",该用户今日付款次数超过限制,如有需要请登录微信支付商户平台更改API安全配置!";break;
                    case "MONEY_LIMIT":msg += ",已经达到今日付款总额上限/已达到付款给此用户额度上限!";break;
                    case "FREQ_LIMIT":msg += ",超过频率限制，请稍后再试!";break;
                    case "CA_ERROR":msg += ",证书出错，请稍后重试!";break;
                    default:break;
                }
                return error(msg);
            }
        }
        return error();
    }
}
